Components.utils.import("resource://app/jsmodules/sbProperties.jsm");
Components.utils.import("resource://app/jsmodules/sbLibraryUtils.jsm");
Components.utils.import("resource://app/jsmodules/sbColumnSpecParser.jsm");
Components.utils.import("resource://app/jsmodules/SBJobUtils.jsm");
Components.utils.import("resource://app/jsmodules/StringUtils.jsm");

var watchLibMain = "";
var hasLyricsProperty = "http://songbirdnest.com/data/1.0#hasLyrics";

var hasLyrObserver = {
 
	_uninstall : false,
	list : null,
	
	observe : function(subject, topic, data) {
		switch(topic) {
			case "em-action-requested":
				// Extension has been flagged to be uninstalled
				subject.QueryInterface(Components.interfaces.nsIUpdateItem);
				if (subject.id == "{248e3e8b-5a5c-4e7e-9bef-6720255e36e0}") {
					if (data == "item-uninstalled") {
						this._uninstall = true;
					} else if (data == "item-cancel-action")
						this._uninstall = false;
				}
				break;
			case "quit-application-granted":
				if (this._uninstall)
					this.uninstallCleanup();
				break;
		}
	},

	register : function() {
		var observerService =
			Components.classes["@mozilla.org/observer-service;1"]
			.getService(Components.interfaces.nsIObserverService);
		observerService.addObserver(this, "em-action-requested", false);
		observerService.addObserver(this, "quit-application-granted", false);
		this.observerService = observerService;

	},

	unregister : function() {
		this.observerService.removeObserver(this, "em-action-requested");
		this.observerService.removeObserver(this, "quit-application-granted");
	},

	uninstallCleanup : function() {
		var mainLib =
			Components.classes['@songbirdnest.com/Songbird/library/Manager;1']
			.getService(Components.interfaces.sbILibraryManager).mainLibrary;
		var colSpec = mainLib.getProperty(SBProperties.columnSpec);
		var propRe = new RegExp("\\s+"+hasLyricsProperty+" \\d+","g");
		if (colSpec.indexOf(hasLyricsProperty)) {
			colSpec = colSpec.replace(propRe, "");
			mainLib.setProperty(SBProperties.columnSpec, colSpec);
		}
		var colSpec = mainLib.getProperty(SBProperties.defaultColumnSpec);
		if (colSpec.indexOf(hasLyricsProperty)) {
			colSpec = colSpec.replace(propRe, "");
			mainLib.setProperty(SBProperties.defaultColumnSpec, colSpec);
		}

	}

};

var watchLib =
{

 init: function()
 {
        watchLibMain = Cc['@songbirdnest.com/Songbird/library/Manager;1'].getService(Ci.sbILibraryManager).mainLibrary;
        
        watchLibMain.addListener(this, false, watchLibMain.LISTENER_FLAGS_ITEMUPDATED | watchLibMain.LISTENER_FLAGS_ITEMADDED);
 },

 onItemUpdated: function(list, item, index)
 {
        var lyrics=item.getProperty("http://songbirdnest.com/data/1.0#lyrics");
        var haslyr=item.getProperty("http://songbirdnest.com/data/1.0#hasLyrics");
        
        if ((lyrics != null) && (haslyr == null))
        {
                item.setProperty("http://songbirdnest.com/data/1.0#hasLyrics", "chrome://lyricmaster/content/images/haslyrics.png");
        }
               
        else if ((lyrics == null) && (haslyr != null))
        {
                item.setProperty("http://songbirdnest.com/data/1.0#hasLyrics", null);
        }
        
 },

 onItemAdded: function(list, item, index)
 {
        var lyrics=item.getProperty("http://songbirdnest.com/data/1.0#lyrics");
         
        if (lyrics != null)
        {
                this.onItemUpdated(list, item, index);
        }

 },


 shutdown: function()
 {
        watchLibMain.removeListener(this);
 }

};

var LM_Base = {
  onLoad: function() {
    if (Application.prefs.getValue("extensions.lyricmaster.firstrun", true))
    {
      dump("running setup of colspec\n");
      try {
      LM_Base.setupColspec();
      } catch (e) {
        dump("exception: " + e + "\n");
      }
      Application.prefs.setValue("extensions.lyricmaster.firstrun", false);
    }

    LM_Base.setupLyricsProperty();
    hasLyrObserver.register();
    watchLib.init();
  },

  onUnLoad: function() {
    watchLib.shutdown();
  },

  // rebuild the column spec strings
  makeSpecString: function(aArray) {
    var spec = "";
    for (var i=0;i<aArray.length;i++) {
      var col = aArray[i];
      if (spec != "") spec += " ";
      spec += col.property;
      if (col.width) {
        spec += " ";
        spec += col.width;
      }
      if (col.sort) {
        if (col.sort == "ascending") {
          col.sort = "a";
        }
        else if (col.sort == "descending") {
          col.sort = "d";
        }
        spec += " ";
        spec += col.sort;
      }
    }
    return spec;
  },

  setupColspec: function() {
    var colSpec = new ColumnSpecParser(LibraryUtils.mainLibrary, null, null,
                                       "audio");
    var colSpecStr = LM_Base.makeSpecString(colSpec.columnMap);
    if (colSpec != null) {
      dump("colspecstr: " + colSpecStr + "\n");
      if (colSpecStr.indexOf(hasLyricsProperty) == -1) {
        ColumnSpecParser.reduceWidthsProportionally(colSpec.columnMap, 45);
        colSpecStr = LM_Base.makeSpecString(colSpec.columnMap) + " " +
                                            hasLyricsProperty + " 10";
        dump("colspecstr new: " + colSpecStr + "\n");
        LibraryUtils.mainLibrary.setProperty(SBProperties.columnSpec+"+(audio)",
                                             colSpecStr);
      }
    }
  },

  setupLyricsProperty: function() {
    var pMgr = Cc["@songbirdnest.com/Songbird/Properties/PropertyManager;1"]
                 .getService(Ci.sbIPropertyManager);
    if (!pMgr.hasProperty(hasLyricsProperty)) {
      var bundle = new SBStringBundle(
                       "chrome://lyricmaster/locale/overlay.properties");
      var builder = Cc["@songbirdnest.com/Songbird/Properties/Builder/Image;1"]
                      .createInstance(Ci.sbIImagePropertyBuilder);
      builder.propertyID = hasLyricsProperty;
      builder.displayName = bundle.get("colLyrLabel", "Lyrics");
      builder.userEditable = false;
      builder.userViewable = true;
      var pI = builder.get();
      pMgr.addPropertyInfo(pI);
    }
  },

  openHelp: function() {
    SBOpenWindow("chrome://lyricmaster/content/help.xul",
                 "lyricmaster",
                 "all,chrome,centerscreen");
  }
};

window.addEventListener("load", function(e) { LM_Base.onLoad(); }, false);
window.addEventListener("unload", function(e) { LM_Base.onUnLoad(); }, false);
